<!-- FamilyUserHome.txt -->
<template>
  <div id="sidemenu">
    <!-- 侧边菜单 -->
    <div
        class="sidebar"
        :class="{ collapsed: isCollapse }"
        :style="{ width: isCollapse ? '0px' : '250px' }"
    >
      <div class="logo-area">
        <div class="logo">
          <i class="el-icon-data-analysis" />
          <span v-if="!isCollapse">
            智慧养老系统<br />
            ——家属端
          </span>
        </div>
        <div v-if="!isCollapse" class="date">{{ currentDate }}</div>
      </div>

      <!-- 菜单列表（略，原逻辑不变） -->
      <div class="menu-section">
        <div class="menu-title">家庭成员与个人中心管理</div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'elderly-bind' }"
            @click="setActiveItem('elderly-bind')"
        >
          <i class="el-icon-user-solid" />
          <span v-if="!isCollapse"> 绑定老人管理</span>
        </div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'family-info' }"
            @click="setActiveItem('family-info')"
        >
          <i class="el-icon-setting" />
          <span v-if="!isCollapse"> 个人信息管理</span>
        </div>
      </div>

      <div class="menu-section">
        <div class="menu-title">健康与安全监护</div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'elderly-health' }"
            @click="setActiveItem('elderly-health')"
        >
          <i class="el-icon-first-aid-kit" />
          <span v-if="!isCollapse"> 健康信息概览</span>
        </div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'medication-reminder' }"
            @click="setActiveItem('medication-reminder')"
        >
          <i class="el-icon-medal" />
          <span v-if="!isCollapse"> 用药提醒设置</span>
        </div>
<!--        <div-->
<!--            class="menu-item"-->
<!--            :class="{ active: activeItem === 'location-outline' }"-->
<!--            @click="setActiveItem('location-outline')"-->
<!--        >-->
<!--          <i class="el-icon-location-outline" />-->
<!--          <span v-if="!isCollapse"> 安全区域设置</span>-->
<!--        </div>-->
        <div
            class="menu-item"
            :class="{ active: activeItem === 'elderly-location' }"
            @click="setActiveItem('elderly-location')"
        >
          <i class="el-icon-location" />
          <span v-if="!isCollapse"> 安全区域与定位</span>
        </div>
      </div>

      <div class="menu-section">
        <div class="menu-title">预警与消息中心</div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'alert-notice' }"
            @click="setActiveItem('alert-notice')"
        >
          <i class="el-icon-bell" />
          <span v-if="!isCollapse"> 预警通知</span>
          <span v-if="!isCollapse" class="notification-badge">3</span>
        </div>
        <div
            class="menu-item"
            :class="{ active: activeItem === 'deal-alert' }"
            @click="setActiveItem('deal-alert')"
        >
          <i class="el-icon-chat-dot-round" />
          <span v-if="!isCollapse"> 处理预警</span>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部信息栏 -->
      <div class="header">
        <div class="header-area">
          <el-icon
              @click="changeCollapse"
              style="margin-left: auto; cursor: pointer;"
          >
            <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                width="24"
                height="24"
            >
              <path
                  d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"
                  fill="black"
              />
            </svg>
          </el-icon>
          <div class="header-title">智慧养老系统——家属端</div>
          <div class="header-subtitle">
            实时监控与管理被照护老人的健康状况
          </div>
        </div>

        <div class="user-info">
          <div class="user-avatar">
            <img
                :src="currentUser.avatarUrl + '?t=' + Date.now()|| defaultAvatar"
                style="width: 40px; height: 40px; border-radius: 50%;"
            />
          </div>
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-name">
              {{ currentUser.username || '未登录' }}
              <el-icon class="arrow-down"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 加载遮罩 -->
      <div v-if="loading" class="loading-overlay">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>加载用户信息中...</span>
      </div>

      <!-- 路由出口 -->
      <router-view v-else />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, provide } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {  ElMessageBox } from 'element-plus'
import axios from 'axios'
import { ArrowDown, SwitchButton, Loading } from '@element-plus/icons-vue'

const BASE_URL = 'http://localhost:8080'
const route = useRoute()
const router = useRouter()

const loading = ref(true)

/* ---------- 用户信息 ---------- */
const userStr = localStorage.getItem('user')
let userData = null
try {
  if (userStr) userData = JSON.parse(userStr)
} catch (e) {
  console.error('解析用户信息失败', e)
  localStorage.removeItem('user')
  router.push('/login')
}

const currentUser = ref({
  userId: userData?.userId || userData?.id || 0,
  username: userData?.username || '',
  realName: userData?.realName || '',
  phone: userData?.phone || '',
  email: userData?.email || '',
  gender: userData?.gender || 0,
  birthDate: userData?.birthDate || '',
  idCard: userData?.idCard || '',
  address: userData?.address || '',
  avatarUrl: userData?.avatarUrl || ''
})

provide('currentUser', currentUser)
/* ---------- 当前被照护老人ID ---------- */
const currentElderlyId = ref(
    Number(route.params.elderlyId) || Number(localStorage.getItem('currentElderlyId')) || null
)

// 添加一个方法用于更新 currentElderlyId
const updateCurrentElderlyId = (id) => {
  currentElderlyId.value = id
  localStorage.setItem('currentElderlyId', String(id))
}
// 把值提供给所有后代组件
provide('currentElderlyId', currentElderlyId)
// 提供更新方法
provide('updateCurrentElderlyId', updateCurrentElderlyId)
/* ---------- 头像默认图 ---------- */
const defaultAvatar = new URL('@/assets/images/default-avatar.png', import.meta.url).href

/* ---------- 刷新用户信息 ---------- */
const refreshUserInfo = async () => {
  const userId = currentUser.value.userId
  if (!userId) return
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const { data } = await axios.get(
        `${BASE_URL}/api/v1/family_user/info/${userId}`,
        { headers: { Authorization: `Bearer ${token}` } }
    )
    if (data.code === 2000) {
      Object.assign(currentUser.value, data.data)
      // 同步到 localStorage，保证刷新页面不丢失
      localStorage.setItem('user', JSON.stringify(currentUser.value))
    }
  } finally {
    loading.value = false
  }
}
provide('refreshUserInfo', refreshUserInfo)

/* ---------- 菜单折叠 ---------- */
const isCollapse = ref(false)
const changeCollapse = () => {
  isCollapse.value = !isCollapse.value
}

/* ---------- 当前日期 ---------- */
const currentDate = computed(() =>
    new Date().toLocaleDateString('zh-CN', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
)

/* ---------- 下拉菜单 ---------- */
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      // 清除 axios 默认 header
      delete axios.defaults.headers.common['Authorization']
      router.push('/login')
    })
  }
}


/* ---------- 菜单激活 ---------- */
const menuMap = {
  'elderly-bind': '/familyuser/bind',
  'family-info': '/familyuser/info',
  'elderly-health': '/familyuser/health',
  'medication-reminder': '/familyuser/medication',
  'location-outline': '/familyuser/zone',
  'elderly-location': '/familyuser/location',
  'alert-notice': '/familyuser/notice',
  'deal-alert': '/familyuser/deal-alert'
}

const activeItem = ref('elderly-bind')   // 默认高亮
const setActiveItem = (item) => {
  activeItem.value = item
  router.push(menuMap[item])
}

// 路由变化时同步高亮
watch(
    () => route.path,
    (path) => {
      const key = Object.keys(menuMap).find(k => menuMap[k] === path)
      if (key) activeItem.value = key
    },
    { immediate: true }
)

watch(
    () => route.params.elderlyId,
    (newId) => {
      if (newId) {
        currentElderlyId.value = Number(newId)
        localStorage.setItem('currentElderlyId', String(newId))
      }
    },
    { immediate: true }
)

/* ---------- 初始化 ---------- */
onMounted(() => {
  if (!currentUser.value.userId) {
    router.push('/login')
    return
  }
  refreshUserInfo()
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}
.loading-overlay {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  gap: 20px;
  color: #666;
}

.loading-icon {
  font-size: 48px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
body {
  background-color: #f8fafc;
  color: #333;
  min-height: 100vh;
  overflow-x: hidden;
}

#sidemenu {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f7ff 0%, #f8fafc 100%);
}

/* 侧边菜单样式 - 优化 */
.sidebar {
  background: linear-gradient(160deg, #2c5282, #1a365d);
  color: #e2e8f0;
  padding: 25px 0;
  box-shadow: 3px 0 20px rgba(0,0,0,0.12);
  z-index: 10;
  position: relative;
  overflow-y: auto;
  transition: all 0.3s ease;
  white-space: nowrap;
}

/* 折叠时的样式 */
.sidebar.collapsed {
  width: 60px !important;
  padding: 25px 0;
}

.logo-area {
  padding: 0 25px 25px;
  border-bottom: 1px solid rgba(255,255,255,0.12);
  margin-bottom: 25px;
}

.logo {
  font-size: 20px;
  font-weight: 700;
  display: flex;
  align-items: center;
  color: #fff;
  line-height: 1.4;
  transition: all 0.3s ease;
}

.sidebar.collapsed .logo {
  justify-content: center;
}

.sidebar.collapsed .logo .logo-text {
  display: none;
}

.sidebar.collapsed .date {
  display: none;
}

.sidebar.collapsed .menu-section {
  padding: 0 15px;
}

.sidebar.collapsed .menu-title {
  font-size: 12px;
  padding-left: 8px;
}

.sidebar.collapsed .menu-item span {
  display: none;
}

.sidebar.collapsed .menu-item i {
  margin-right: 0;
}

.sidebar.collapsed .menu-item.active::before {
  left: 0;
  height: 100%;
}

.logo i {
  margin-right: 12px;
  font-size: 28px;
  color: #63b3ed;
  background: rgba(255,255,255,0.08);
  padding: 10px;
  border-radius: 12px;
}

.date {
  font-size: 14px;
  color: #a0aec0;
  margin-top: 12px;
  margin-left: 52px;
  font-weight: 400;
}

.menu-section {
  margin-bottom: 32px;
  padding: 0 25px;
}

.menu-title {
  font-size: 15px;
  font-weight: 600;
  color: #90cdf4;
  margin-bottom: 20px;
  letter-spacing: 0.5px;
  position: relative;
  padding-left: 12px;
  display: flex;
  align-items: center;
}

.menu-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 16px;
  width: 3px;
  background: #4299e1;
  border-radius: 2px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 14px 18px;
  border-radius: 10px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 15px;
  position: relative;
  background: rgba(255, 255, 255, 0.05);
}

.menu-item:hover {
  background: rgba(255,255,255,0.12);
}

.menu-item.active {
  background: linear-gradient(90deg, #3182ce, #2b6cb0);
  color: white;
  box-shadow: 0 4px 12px rgba(49, 130, 206, 0.25);
}

.menu-item i {
  margin-right: 14px;
  width: 24px;
  text-align: center;
  font-size: 18px;
}

.notification-badge {
  position: absolute;
  right: 18px;
  background: #e53e3e;
  color: white;
  font-size: 12px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
}

/* 主内容区域样式 - 优化 */
.main-content {
  flex: 1;
  padding: 30px 35px;
  overflow-y: auto;
  background: #f8fafc;
  transition: all 0.3s ease;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-area {
  padding-bottom: 15px;
  border-bottom: 2px solid #ebf8ff;
}

.header-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  position: relative;
  padding-left: 0;
  margin-bottom: 8px;
}

.header-title::before {
  display: none;
}

.header-subtitle {
  font-size: 16px;
  color: #718096;
  font-weight: 500;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 18px;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  //background: linear-gradient(135deg, #4299e1, #3182ce);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 18px;
  box-shadow: 0 4px 8px rgba(66, 153, 225, 0.3);
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

/* 功能横幅 - 优化 */
.function-banner {
  background: linear-gradient(135deg, #4299e1, #3182ce);
  border-radius: 16px;
  padding: 25px 30px;
  color: white;
  margin-bottom: 35px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8px 20px rgba(66, 153, 225, 0.3);
  position: relative;
  overflow: hidden;
}

.function-banner::before {
  content: '';
  position: absolute;
  top: -40px;
  right: -40px;
  width: 150px;
  height: 150px;
  background: rgba(255,255,255,0.12);
  border-radius: 50%;
}

.banner-content h3 {
  font-size: 24px;
  margin-bottom: 12px;
  font-weight: 700;
}

.banner-content p {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 20px;
  max-width: 500px;
}

.function-btn {
  background: white;
  color: #3182ce;
  border: none;
  padding: 12px 28px;
  border-radius: 30px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  font-size: 15px;
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.function-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.2);
  background: #ebf8ff;
}

.banner-icon i {
  font-size: 80px;
  opacity: 0.15;
  position: absolute;
  right: 40px;
  top: 50%;
  transform: translateY(-50%);
}

/* 健康指标卡片样式 */
.metrics-row {
  margin-bottom: 35px;
}

.health-card {
  background: white;
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.06);
  height: 100%;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  overflow: hidden;
  border: none;
  display: flex;
  align-items: center;
  gap: 20px;
}

.health-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
}

.metric-icon {
  width: 70px;
  height: 70px;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: white;
}

.card-heart .metric-icon {
  background: linear-gradient(135deg, #e53e3e, #c53030);
}

.card-pressure .metric-icon {
  background: linear-gradient(135deg, #805ad5, #6b46c1);
}

.card-sleep .metric-icon {
  background: linear-gradient(135deg, #319795, #2c7a7b);
}

.card-activity .metric-icon {
  background: linear-gradient(135deg, #38a169, #2f855a);
}

.metric-info {
  flex: 1;
}

.metric-title {
  font-size: 16px;
  color: #718096;
  margin-bottom: 8px;
  font-weight: 500;
}

.metric-value {
  font-size: 32px;
  font-weight: 800;
  color: #2d3748;
  margin-bottom: 5px;
  display: flex;
  align-items: flex-end;
}

.unit {
  font-size: 16px;
  font-weight: 500;
  margin-left: 6px;
  color: #718096;
}

.metric-change {
  font-size: 14px;
  color: #38a169;
  display: flex;
  align-items: center;
  gap: 6px;
}

.card-sleep .metric-change {
  color: #e53e3e;
}

/* 健康数据区域 */
.health-data-section {
  background: white;
  border-radius: 16px;
  padding: 25px 30px;
  box-shadow: 0 8px 20px rgba(0,0,0,0.06);
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.section-header h3 {
  font-size: 20px;
  font-weight: 700;
  color: #2d3748;
}

.time-filter {
  display: flex;
  gap: 15px;
  background: #edf2f7;
  padding: 6px;
  border-radius: 30px;
}

.time-filter span {
  padding: 6px 16px;
  border-radius: 30px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.time-filter span.active {
  background: #4299e1;
  color: white;
  font-weight: 500;
}
.arrow-down {
  color: #4299e1;
  font-size: 12px;
  transition: transform 0.3s;
}

.data-placeholder {
  height: 300px;
  background: #f8fafc;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #a0aec0;
  border: 1px dashed #cbd5e0;
}

.data-placeholder i {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.data-placeholder p {
  font-size: 18px;
  font-weight: 500;
}

/* 图表画布 */
canvas {
  width: 100% !important;
  max-height: 230px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .sidebar {
    width: 240px;
  }
}

@media (max-width: 992px) {
  #sidemenu {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    height: auto;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 20px 15px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .user-info {
    width: 100%;
    justify-content: flex-end;
  }

  .function-banner {
    flex-direction: column;
    text-align: center;
  }

  .banner-icon {
    display: none;
  }

  .health-card {
    flex-direction: column;
    text-align: center;
  }
}
</style>